package net.starwifi.duobao.service.impl;


import net.starwifi.duobao.AppInitListener;
import net.starwifi.duobao.entity.Member;
import net.starwifi.duobao.entity.TradeRecord;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.service.MemberService;
import net.starwifi.duobao.service.TradeRecordService;
import net.starwifi.duobao.service.TransferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * Created by Administrator on 2015/9/29.
 */
@Service
public class TransferServiceImpl implements TransferService {


    @Autowired
    MemberService memberService;

    @Autowired
    TradeRecordService tradeRecordService;

    @Transactional
    public Message hb(Long currentMemberId,String mobile,BigDecimal fee){
        Member currentMember=memberService.find(currentMemberId);
        Member memberTwo=memberService.findByMobile(mobile);
        if(memberTwo==null){
            return Message.error("对方账户不存在");
        }
        if(!currentMember.getIsEnabled()){
            return Message.error("账户被锁定,无法操作");
        }
        if(!memberTwo.getIsEnabled()){
            return Message.error("对方账户冻结状态,无法接收");
        }
        if(currentMember.getBalance().doubleValue()<fee.doubleValue()){
            return Message.error("账户余额不足");
        }
        currentMember.setBalance(currentMember.getBalance().subtract(fee));//账户金额减少
        memberTwo.setBalance(memberTwo.getBalance().add(fee)); //账户金额增加
        memberService.update(currentMember);
        memberService.update(memberTwo);
        //日志
        String sn=AppInitListener.idGenerate.getID().toString();
        String snTwo=AppInitListener.idGenerate.getID().toString();
        TradeRecord trOne=new TradeRecord(sn,0,fee, "红包发送给"+memberTwo.getMobile(),currentMember.getId());
        trOne.setTradeCat(1);
        trOne.setOutSn(snTwo);
        TradeRecord trTwo=new TradeRecord(snTwo,1,fee, "接收到"+currentMember.getMobile()+"的红包",memberTwo.getId());
        trTwo.setTradeCat(1);
        trOne.setOutSn(sn);
        tradeRecordService.save(trOne);
        tradeRecordService.save(trTwo);
        return Message.success("红包发送成功");
    }

}
